﻿using BusinessLogic.BusinessEntity.Entities;
using BusinessLogic.Cryptography;
using BusinessLogic.Mappers;
using Common.Tests;
using DataAccess.Services;

namespace BusinessLogic.Managers.Tests.Models
{
	class RAModel
	{
		public static RemittanceAdvice Create()
		{
			var ra = new RemittanceAdvice();

			ra.BillToPartyAccount = AccountModel.Create();
			ra.Currency = CurrencyModel.Create();
			ra.Description = TestHelper.RandomString;
			ra.Number = TestHelper.Random.Next().ToString();
			ra.PayerPartyAccount = AccountModel.Create();
			ra.TotalAmount = TestHelper.RandomDecimal;

			if(ra.TotalAmount > ra.PayerPartyAccount.Balance)
			{
				ra.PayerPartyAccount.Balance += ra.TotalAmount;
			}

			return ra;
		}

		public static string PrepareDB(RemittanceAdvice ra)
		{
			var keys = RSADigitalSignatureManager.GenerateRSAKeys();
			string privateKey = keys.PrivateKey;
			ra.PayerPartyAccount.Accountee.PublicKey = keys.PublicKey;

			using (IServiceManager serviceManager = new ServiceManager())
			{
				var currency = CurrencyModel.Create();
				ra.BillToPartyAccount.Currency = currency;
				ra.PayerPartyAccount.Currency = currency;
				ra.Currency = currency;

				MapperFactory.GetCurrencyMapper(serviceManager).Insert(currency);
				MapperFactory.GetCurrencyConversionMapper(serviceManager).Insert(new CurrencyConversion
				                                                                 	{
				                                                                 		ConversionRate = 1,
				                                                                 		SourceCurrency = currency,
				                                                                 		TargetCurrency = currency
				                                                                 	});

				MapperFactory.GetUserMapper(serviceManager).Insert(ra.BillToPartyAccount.Accountee);
				MapperFactory.GetUserMapper(serviceManager).Insert(ra.PayerPartyAccount.Accountee);

				MapperFactory.GetAccountMapper(serviceManager).Insert(ra.BillToPartyAccount);
				MapperFactory.GetAccountMapper(serviceManager).Insert(ra.PayerPartyAccount);
			}

			return privateKey;
		}
	}
}
